#include "cameraThread.h"
#include <QDebug>
#include <QImage>
#include <QPixmap>
#include <QLabel>
#include <QDebug>

// 将cv::Mat转换为QImage
QImage cvMatToQImage(const cv::Mat &mat) {
    switch(mat.type()) {
        // 8位4通道
        case CV_8UC4: {
            QImage image(mat.data, mat.cols, mat.rows,
                         static_cast<int>(mat.step),
                         QImage::Format_ARGB32);
            return image.copy(); // 防止原始数据被修改
        }
        // 8位3通道
        case CV_8UC3: {
            QImage image(mat.data, mat.cols, mat.rows,
                         static_cast<int>(mat.step),
                         QImage::Format_RGB888);
            return image.rgbSwapped().copy(); // OpenCV是BGR，Qt需要RGB
        }
        // 8位1通道
        case CV_8UC1: {
            QImage image(mat.data, mat.cols, mat.rows,
                         static_cast<int>(mat.step),
                         QImage::Format_Grayscale8);
            return image.copy();
        }
        default:
            qWarning() << "Unsupported cv::Mat type:" << mat.type();
            return QImage();
    }
}

CameraThread::CameraThread(QObject *parent) : QThread(parent)
{

}

CameraThread::~CameraThread()
{
    stopCamera();
}

void CameraThread::CameraInit(int index)
{
    m_cameraIndex = index;
    if(index == 1)
    {
        m_d435Camera = std::make_unique<D435Camera>();
        m_d435Camera->init();
    }
    else if(index ==2)
    {
        m_orb336l = std::make_unique<orb336LCamera>();
    }
}

void CameraThread::startCamera()
{
    std::cout << "startCamera" << std::endl;
    QMutexLocker locker(&m_mutex);
    m_stop = false;

    if(!isRunning())
    {
        start();
    }
}

void CameraThread::stopCamera()
{
    QMutexLocker locker(&m_mutex);
    m_stop = true;
    if(m_cameraIndex == 1)
    {
        m_d435Camera->closeCamera();
    }
    else if(m_cameraIndex ==2)
    {
        m_orb336l->stopCamera();
    }

    wait(); // 等待线程结束
}

void CameraThread::run()
{
    std::cout << "run" << std::endl;

    cv::Mat image;

    if(m_cameraIndex == 1)
    {
        while(true)
        {
            if(!m_d435Camera->getFrame(image)) {
                break;
            }

            QImage qimage = cvMatToQImage(image);
            if(!qimage.isNull())
            {
                {
                    QMutexLocker locker(&m_mutex);
                    emit frameReady(qimage);
                }
            }
            QThread::msleep(10);

        }

    }
    else if(m_cameraIndex == 2)
    {
        while(true)
        {
            if(!m_orb336l->getColorFrame(image)){
                break;
            }

            QImage qimage = cvMatToQImage(image);
            if(!qimage.isNull())
            {
                {
                    QMutexLocker locker(&m_mutex);
                    emit frameReady(qimage);
                }
            }
            QThread::msleep(10);
        }
    }


}
